package com.nd.android.u.ui.widge;

import ims.manager.IMSStateManager;
import ims.utils.SdCardUtils;

import java.util.ArrayList;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.StarAppConfig;
import com.common.allCommon.CommUtil;
import com.common.android.utils.smiley.Smileyhelper;
import com.common.utils.StarAppUtils;
import com.common.widget.CommonTipDlg;
import com.common.widget.CommonTipDlg.OnCommonDlgClickListener;
import com.nd.android.u.allCommonUtils.FileHelper;
import com.nd.android.u.allCommonUtils.ToastUtils;
import com.nd.android.u.allCommonUtils.UrlUtils;
import com.nd.android.u.chatInterfaceImpl.ChatInterfaceImpl;
import com.nd.android.u.controller.ChatConst.LocalMessageType;
import com.nd.android.u.controller.ChatConst.MessageContentType;
import com.nd.android.u.controller.ChatGlobalVariable;
import com.nd.android.u.controller.MessageConst.MessageState;
import com.nd.android.u.controller.bean.ImageMessage;
import com.nd.android.u.controller.bean.message.BaseDisplayMessage;
import com.nd.android.u.controller.factory.MessageFactory;
import com.nd.android.u.controller.factory.MessageLongClickMenuFactory;
import com.nd.android.u.controller.factory.ShareFileFactory;
import com.nd.android.u.controller.innerInterface.IChatListItem;
import com.nd.android.u.controller.innerInterface.IMessageDisplay;
import com.nd.android.u.controller.innerInterface.IShareFile;
import com.nd.android.u.ui.ChatEntry;
import com.nd.android.u.ui.R;
import com.nd.android.u.ui.activity.chat_relative_image.ShowImagesActivity;
import com.nd.android.u.ui.activity.message_chat.ChangeTypefaceCallBack;
import com.product.android.business.ApplicationVariable;
import com.product.android.business.Const;
import com.product.android.commonInterface.BaseCommonStruct;

import de.greenrobot.event.EventBus;

/**
 * 聊天列表控件（父容器） <br>
 * Created 2014-5-7 下午3:17:37
 *
 * @version
 * @author cb
 * @see
 */
@SuppressLint("UseSparseArrays")
public class ChatListItemView extends LinearLayout implements IChatListItem {
    private LinearLayout heLayout;
    private LinearLayout myLayout;
    private ImageView heface;
    private ImageView myface;
    private TextView timeText;
    private TextView heUserNameText;
    private ProgressBar pbLoadingMy;
    private ProgressBar pbLoadingOthers;
    private ImageView imgFailMy;
    private ImageView imgFailOthers;
    private LinearLayout myContentLayout;
    private LinearLayout heContentLayout;
    private TextView tvUnread;
    private TextView tvMyDuration;
    private TextView tvHeDuration;
    private RelativeLayout rlRead;
    private IMessageDisplay mDispalyingMessage;
    private Context mContext;
    private LinearLayout mDisplayLayout; // 当前用于加载子控件的容器

    // “我”这边已加载的控件
    private HashMap<Integer, IChatListItem> mMyViews = new HashMap<Integer, IChatListItem>();

    // “他”那边已加载的控件
    private HashMap<Integer, IChatListItem> mHeViews = new HashMap<Integer, IChatListItem>();

    // 当前已加载的控件MAP（mMyViews和mHeViews之一）
    private HashMap<Integer, IChatListItem> mDisplayViews;

    // 当前正在显示的控件
    private IChatListItem mDisplayingView;

    public ChatListItemView(Context context) {
        super(context);
        this.mContext = context;
        EventBus.getDefault().register(this,BaseCommonStruct.class);
        getView();
    }

    /**
     * 设置改变字体回调 <br>
     * Created 2014-9-17 下午11:10:45
     *
     * @param callBack
     *            改变字体回调
     * @author cb
     */
    public void setChangeTypefaceCallBack(ChangeTypefaceCallBack callBack) {
        callBack.changeType(timeText);
        callBack.changeType(heUserNameText);
        callBack.changeType(tvMyDuration);
        callBack.changeType(tvHeDuration);
    }

    /**
     * 初始化控件 <br>
     * Created 2014-5-7 下午3:18:14
     *
     * @author cb
     */
    protected void getView() {
        LayoutInflater.from(mContext).inflate(R.layout.chat_list_item, this,
                true);
        heLayout = (LinearLayout) findViewById(R.id.messagedetail_row_layout_he);
        myLayout = (LinearLayout) findViewById(R.id.messagedetail_row_layout_me);
        myContentLayout = (LinearLayout) findViewById(R.id.llMyContent);
        heContentLayout = (LinearLayout) findViewById(R.id.llOthersContent);
        timeText = (TextView) findViewById(R.id.messagedetail_time_tv);
        myface = (ImageView) findViewById(R.id.messagedetail_row_face_me);
        heface = (ImageView) findViewById(R.id.messagedetail_row_face_he);

        heUserNameText = (TextView) findViewById(R.id.messagedetail_heusername_tv);
        pbLoadingMy = (ProgressBar) findViewById(R.id.pbLoadingMy);
        pbLoadingOthers = (ProgressBar) findViewById(R.id.pbLoadingOthers);
        imgFailMy = (ImageView) findViewById(R.id.imgFailMy);
        imgFailMy.setOnClickListener(clickFailimg);
        imgFailOthers = (ImageView) findViewById(R.id.imgFailOthers);
        imgFailOthers.setOnClickListener(clickFailimg);
        tvUnread = (TextView) findViewById(R.id.tvUnread);
        tvMyDuration = (TextView) findViewById(R.id.tvMyDuration);
        tvHeDuration = (TextView) findViewById(R.id.tvOthersDuration);
        rlRead = (RelativeLayout) findViewById(R.id.rlRead);
        heContentLayout.setOnLongClickListener(mLongClickListener);
        myContentLayout.setOnLongClickListener(mLongClickListener);
        heContentLayout.setOnClickListener(clickBubble);
        myContentLayout.setOnClickListener(clickBubble);

        initTpyeface();
    }

    /**
     * 设置字体
     *
     * <br>
     * Created 2014-10-21 上午11:26:55
     *
     * @author : HuangYK
     */
    private void initTpyeface() {
        StarAppUtils.setViewTypeFace(timeText, false);
        StarAppUtils.setViewTypeFace(heUserNameText, false);
        StarAppUtils.setViewTypeFace(tvMyDuration, false);
        StarAppUtils.setViewTypeFace(tvHeDuration, false);
    }

    /**
     * 设置数据源 <br>
     * Created 2014-5-7 下午3:18:41
     *
     * @param message
     * @author cb
     */
    public void setData(IMessageDisplay message) {
        // 显示时间和头像
        timeText.setVisibility(View.VISIBLE);
        String time = message.getTimeString();
        if (TextUtils.isEmpty(time)) {
            timeText.setVisibility(View.GONE);
        } else {
            timeText.setText(time);
            timeText.setVisibility(View.VISIBLE);
        }
		Object bTag = getTag();
		if(bTag!=null && bTag instanceof Boolean && (Boolean)bTag){
			showUserFace(message,true);
		}else{
			showUserFace(message,false);
		}
        // 设置字体大小
        timeText.setTextSize(ChatGlobalVariable.getInstance()
                .getChatTimeTextSize());
        heUserNameText.setTextSize(ChatGlobalVariable.getInstance()
                .getChatTimeTextSize());
        if (message.getMessageType() == LocalMessageType.GROUP) {
            String name = ChatInterfaceImpl.INSTANCE.chatCallOtherModel
                    .getUserName(((BaseDisplayMessage) message).uidFrom);
            heUserNameText.setText(name);
            heUserNameText.setVisibility(View.VISIBLE);
        } else {
            heUserNameText.setVisibility(View.GONE);
        }
        rlRead.setVisibility(View.GONE);
        // 根据消息的来源控制控件布局
        if (message.isFromSelf()) {
            // 自己发的消息（转账应用消息只显示在左侧）
            heLayout.setVisibility(View.GONE);
            myLayout.setVisibility(View.VISIBLE);
            mDisplayLayout = myContentLayout;
            mDisplayViews = mMyViews;
        } else {
            heLayout.setVisibility(View.VISIBLE);
            myLayout.setVisibility(View.GONE);
            mDisplayLayout = heContentLayout;
            mDisplayViews = mHeViews;
        }

        myface.setOnClickListener(clickPortrait);

        // if (ChatInterfaceImpl.INSTANCE.chatCallOtherModel
        // .isInMyFriendGroup(((BaseDisplayMessage) message).uidFrom)) {
        heface.setOnClickListener(clickPortrait);
        // }else{
        // heface.setOnClickListener(null);
        // }

        tvUnread.setVisibility(View.GONE);
        tvMyDuration.setVisibility(View.GONE);
        tvHeDuration.setVisibility(View.GONE);
        imgFailMy.setVisibility(View.GONE);
        imgFailOthers.setVisibility(View.GONE);
        pbLoadingMy.setVisibility(View.GONE);
        pbLoadingOthers.setVisibility(View.GONE);
        // 根据消息的状态来确定上传中及失败标识的显示
        int extraFlag = message.getExtraFlag();
        int contentType = message.getMessageContentType();
        switch (extraFlag) {
            case MessageState.UPLOADING:
            case MessageState.DOWNLOADING:
            case MessageState.SENDING:
                if (isShowProgress(contentType)) {
                    // 需要显示进度
                    if (message.isFromSelf()) {
                        tvMyDuration.setVisibility(View.VISIBLE);
                        tvMyDuration.setText(message.getProgress());
                    } else {
                        rlRead.setVisibility(View.VISIBLE);
                        tvHeDuration.setVisibility(View.VISIBLE);
                        tvHeDuration.setText(message.getProgress());
                    }
                } else {
                    pbLoadingMy.setVisibility(View.VISIBLE);
                    pbLoadingOthers.setVisibility(View.VISIBLE);
                }
                break;
            case MessageState.SEND_FAIL:
            case MessageState.UPLOAD_FAIL:
            case MessageState.DOWNLOAD_FAIL:
                imgFailMy.setVisibility(View.VISIBLE);
                imgFailOthers.setVisibility(View.VISIBLE);
                break;
            case MessageState.RECEIVED:
                if (isShowProgress(contentType)) {
                    rlRead.setVisibility(View.VISIBLE);
                    tvHeDuration.setVisibility(View.VISIBLE);
                    tvHeDuration.setText("0%");
                }
                break;
            default:
                if (contentType == MessageContentType.AUDIO
                        || contentType == MessageContentType.OLD_AUDIO
                        || contentType == MessageContentType.VIDEO
                        || contentType == MessageContentType.MULTI_MEDIA) {
                    // 如果是语音/视频消息才显示下面的控件
                    if (extraFlag == MessageState.RECEIVED) {
                        // 刚收到的语音消息，显示Loading
                        pbLoadingMy.setVisibility(View.VISIBLE);
                        pbLoadingOthers.setVisibility(View.VISIBLE);
                    } else {
                        rlRead.setVisibility(View.VISIBLE);
                        if (!message.isRead()) {
                            tvUnread.setVisibility(View.VISIBLE);
                        }
                        if (message.isFromSelf()) {
                            tvMyDuration.setVisibility(View.VISIBLE);
                            tvMyDuration.setText(message.getDuration() + "\"");
                        } else {
                            tvHeDuration.setVisibility(View.VISIBLE);
                            tvHeDuration.setText(message.getDuration() + "\"");
                        }
                    }
                }
                break;
        }
        addSubView(message);
    }

    /**
     * 是否显示进度 <br>
     * Created 2014-6-24 下午10:47:53
     *
     * @param contentType
     *            消息类型
     * @return boolean
     * @author cb
     */
    private boolean isShowProgress(int contentType) {
        if (contentType == MessageContentType.AUDIO
                || contentType == MessageContentType.OLD_AUDIO
                || contentType == MessageContentType.VIDEO) {
            return true;
        }
        return false;
    }

    /**
     * 添加具体的消息内容视图 <br>
     * Created 2014-5-6 下午2:57:55
     *
     * @param message 消息体
     * @author cb
     */
    private void addSubView(IMessageDisplay message) {
        if (mDisplayingView != null) {
            ((View) mDisplayingView).setVisibility(View.GONE);
            mDisplayingView = null;
        }
        int viewType = message.getViewType();
        if (mDisplayViews.containsKey(viewType)) {
            mDisplayingView = mDisplayViews.get(viewType);
        }
        if (mDisplayingView == null) {
            mDisplayingView = MessageFactory.INSTANCE.getMessageView(mContext,
                    message, false);
        }
        if (!mDisplayViews.containsValue(mDisplayingView)) {
            // 当前已加载的控件表里没有正要显示的这个控件，要把它加进去
            mDisplayViews.put(viewType, mDisplayingView);
            mDisplayLayout.addView((View) mDisplayingView);
        }
        ((View) mDisplayingView).setVisibility(View.VISIBLE);
        mDisplayingView.setData(message);
        // 以下代码是为了解决在某些机型上显示大的图之后再复用的话长宽会和原来的一样大的BUG
        LinearLayout.LayoutParams lp = (LayoutParams) ((View) mDisplayingView)
                .getLayoutParams();
        if (lp == null) {
            lp = new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
        } else {
            lp.width = LayoutParams.WRAP_CONTENT;
            lp.height = LayoutParams.WRAP_CONTENT;
        }
//		lp.weight = 1;
        ((View) mDisplayingView).setLayoutParams(lp);
        mDispalyingMessage = message;
        String text = mDispalyingMessage.getDisplayContent();
//		if(UrlUtils.isHtml(text)){
//			heContentLayout.setOnLongClickListener(null);
//			myContentLayout.setOnLongClickListener(null);
//		}else{
//			heContentLayout.setOnLongClickListener(mLongClickListener);
//			myContentLayout.setOnLongClickListener(mLongClickListener);
//		}
    }

    /**
     * 显示头像 <br>
     * Created 2014-5-6 下午2:21:52
     *
     * @param message
     * @author cb
     */
	protected void showUserFace(IMessageDisplay message,boolean isNeedUpdate) {
		if ((mDispalyingMessage != null && mDispalyingMessage.equals(message))&& !isNeedUpdate) {
			return;
		}

        mDispalyingMessage = message;
        setTag(false);

        long uid = 0;

        if (mDispalyingMessage instanceof BaseDisplayMessage) {
            uid = ((BaseDisplayMessage) mDispalyingMessage).uidFrom;
        }
        boolean isStarMsg = (uid != 0 && String.valueOf(uid).equals(StarAppConfig.getConfig(StarAppConfig.JAY_UID)));

        if (message.isFromSelf()) {
            myface.setVisibility(View.VISIBLE);
            heface.setVisibility(View.GONE);
            if (isStarMsg) {
                myface.setBackgroundResource(R.drawable.bg_avator_of_star_frame);
            }else{
                myface.setBackgroundResource(R.drawable.common_avator_translucent_frame);
            }
            heface.setBackgroundResource(R.drawable.common_avator_translucent_frame);
            message.displayPortrait(myface, true);
        } else {
            myface.setVisibility(View.GONE);
            heface.setVisibility(View.VISIBLE);
            if (isStarMsg) {
                heUserNameText.setTextColor(getResources().getColor(R.color.common_name_of_star_color));
                heface.setBackgroundResource(R.drawable.bg_avator_of_star_frame);
            }else{
                heUserNameText.setTextColor(getResources().getColor(R.color.common_light_gray));
                heface.setBackgroundResource(R.drawable.common_avator_translucent_frame);
            }
            myface.setBackgroundResource(R.drawable.common_avator_translucent_frame);
            message.displayPortrait(heface, false);
        }
    }

    // clickPortrait:点击头像
    private OnClickListener clickPortrait = new OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean isMyPortrait;
            if (v.getId() == R.id.messagedetail_row_face_me) {
                isMyPortrait = true;
            } else {
                isMyPortrait = false;
            }
            mDispalyingMessage.clickPortrait(isMyPortrait, mContext);
        }
    };

    // clickPortrait:点击头像
//    private OnClickListener clickMyPortrait = new OnClickListener() {
//        @Override
//        public void onClick(View v) {
//            mDispalyingMessage.clickPortrait(v.equals(myface), mContext);
//            ChatEntry.INSTANCE.chatCallOtherModel_UI
//                    .gotoPersonalDynamicActivity(mContext,
//                            ((BaseDisplayMessage) mDispalyingMessage).uidFrom);
//        }
//    };

    /**
     * clickFailimg:点击失败图标
     */
    private OnClickListener clickFailimg = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mDispalyingMessage.isFromSelf()) {

                CommonTipDlg ctd = new CommonTipDlg(mContext,
                        mContext.getString(R.string.chat_pop_resend_note),
                        mContext.getString(R.string.chat_stranger_cancel),
                        mContext.getString(R.string.chat_pop_resend_msg),
                        R.style.common_dialog_style);
                ctd.setLayoutResID(R.layout.common_tip_dlg_pink);
                ctd.setOnListener(new OnCommonDlgClickListener() {

                    @Override
                    public void onRightBtnClicked() {
                        // 重发
                        switch (mDispalyingMessage.getExtraFlag()) {
                            case MessageState.UPLOAD_FAIL:
                            case MessageState.SEND_FAIL:
                                if (IMSStateManager.getInstance()
                                        .isNetworkAvailable()) {
                                    // 有网络
                                    mDispalyingMessage.resend();
                                } else {
                                    ToastUtils.display(mContext,
                                            R.string.net_warn_no_network);
                                }
                                break;
                            case MessageState.DOWNLOAD_FAIL:
                                if (IMSStateManager.getInstance()
                                        .isNetworkAvailable()) {
                                    // 有网络
                                    mDispalyingMessage.doDownload();
                                } else {
                                    ToastUtils.display(mContext,
                                            R.string.net_warn_no_network);
                                }
                                break;
                        }
                    }

                    @Override
                    public void onLeftBtnClicked() {
                        // 取消不做任何操作
                    }
                });
                ctd.setCanceledOnTouchOutside(true);
                ctd.show();
            } else {
                // 下载失败
                if (IMSStateManager.getInstance().isNetworkAvailable()) {

                    CommonTipDlg ctd = new CommonTipDlg(mContext,
                            mContext.getString(R.string.chat_pop_audio_redown_note),
                            mContext.getString(R.string.chat_stranger_cancel),
                            mContext.getString(R.string.chat_pop_reDown_msg),
                            R.style.common_dialog_style);
                    ctd.setLayoutResID(R.layout.common_tip_dlg_pink);
                    ctd.setOnListener(new OnCommonDlgClickListener() {

                        @Override
                        public void onRightBtnClicked() {

                            if (IMSStateManager.getInstance()
                                    .isNetworkAvailable()) {
                                // 有网络
                                mDispalyingMessage.doDownload();
                            }
                        }

                        @Override
                        public void onLeftBtnClicked() {
                            // 取消不做任何操作
                        }
                    });
                    ctd.setCanceledOnTouchOutside(true);
                    ctd.show();
                }
            }
        }
    };

    // clickBubble:点击气泡体
    private OnClickListener clickBubble = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mDisplayingView instanceof ChatListItemView_Image) {
                String path = mDispalyingMessage.getPath();
                if (mDispalyingMessage.isFromSelf() && !TextUtils.isEmpty(path)) {
                    viewLocalImg(path, mDispalyingMessage.getThumbnailPath());
                } else {
                    ArrayList<Object> datas = mDispalyingMessage
                            .getDisplayDatas();
                    ArrayList<String> imgUrlList = new ArrayList<String>();
                    ArrayList<String> thumbUrlList = new ArrayList<String>();
                    for (Object obj : datas) {
                        if (obj instanceof ImageMessage) {
                            ImageMessage imageMessage = (ImageMessage) obj;
                            // 这里判断如果是猫表情，那就直接返回不浏览大图
                            if (imageMessage.getType() == ImageMessage.SMILY_TYPE) {
                                int id = CommUtil.parseInt(imageMessage
                                        .getImgurl());
                                if (Smileyhelper.getInstance().isCatID(id)) {
                                    return;
                                }
                            }
                            int type = MessageContentType.PICTURE;
                            IShareFile shareFile = ShareFileFactory.INSTANCE
                                    .getShareFileInterface(IShareFile.DOWNLOAD,
                                            type);
                            String url = shareFile.getShareFileUrl(
                                    imageMessage.getImgurl(), "", type);
                            imgUrlList.add(url);
                            if (ApplicationVariable.INSTANCE.displayMetrics.heightPixels > 1000
                                    || ApplicationVariable.INSTANCE.displayMetrics.widthPixels > 1000) {
                                url += "&thumb=440";
                            } else {
                                url += "&thumb=120";
                            }
                            thumbUrlList.add(url);
                        }
                    }
                    viewImg(imgUrlList, thumbUrlList);
                }
            }
        }
    };

    /**
     * 查看本地图片 <br>
     * Created 2014-7-22 下午6:07:53
     *
     * @author cb
     */
    private void viewLocalImg(String path, String thumbPath) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        ArrayList<String> imgUrlList = new ArrayList<String>();
        imgUrlList.add(FileHelper.getFileUri(path));
        if (!TextUtils.isEmpty(thumbPath)) {
            // 如果有缩略图,把相应的路径送过去.
            ArrayList<String> thumbUrlList = new ArrayList<String>();
            thumbUrlList.add(FileHelper.getFileUri(thumbPath));
            bundle.putStringArrayList(Const.BUNDLE_KEY.THUMB_LIST, thumbUrlList);
        }
        bundle.putStringArrayList(Const.BUNDLE_KEY.URL_LIST, imgUrlList);
        bundle.putBoolean("chat", true);
        intent.putExtras(bundle);
        intent.setClass(mContext, ShowImagesActivity.class);
        mContext.startActivity(intent);
    }

    /**
     * 查看网络图片 <br>
     * Created 2014-7-22 下午6:15:12
     *
     * @param imgUrlList
     * @param thumbUrlList
     * @author cb
     */
    private void viewImg(ArrayList<String> imgUrlList,
                         ArrayList<String> thumbUrlList) {
        if (!SdCardUtils.isSdCardExist()) {
            ToastUtils.display(R.string.sdcard_not_found);
            return;
        }
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putStringArrayList(Const.BUNDLE_KEY.URL_LIST, imgUrlList);
        bundle.putStringArrayList(Const.BUNDLE_KEY.THUMB_LIST, thumbUrlList);
        bundle.putBoolean("chat", true);
        intent.putExtras(bundle);
        intent.setClass(mContext, ShowImagesActivity.class);
        mContext.startActivity(intent);
    }

    // mLongClickListener:控件长按事件
    private OnLongClickListener mLongClickListener = new OnLongClickListener() {
        @Override
        public boolean onLongClick(View arg0) {
            MessageLongClickMenuFactory.getInstance().show(mContext,
                    mDispalyingMessage);
            return false;
        }
    };

    /**
     * 获取数据 <br>
     * Created 2014-7-27 下午9:46:26
     *
     * @return
     * @author cb
     */
    public IMessageDisplay getData() {
        return mDispalyingMessage;
    }

    /**
     * EventBus接收函数,更新头像
     *
     * <br>
     * Created 2014-10-29 下午4:07:30
     *
     * @param struct
     *            传递的数据
     * @author : ChuXY
     */
    public void onEventMainThread(BaseCommonStruct struct) {
        CommUtil.updateSculptureImageShown(struct, heface);
    }

}
